﻿using SportsPlatform.Consts;
using SportsPlatform.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SqlSugar;
using System.Threading.Tasks;
using SportsPlatform.Helpers;
using Abp.ObjectMapping;
using SportsPlatform.PermissionManagement.PermissionManagement;
using SportsPlatform.SportBusiness.ISportBusiness;
using SportsPlatform.Dto.SportBusiness.Category;
using SportsPlatform.Query.SportBusiness.Category;
using SportsPlatform.Model.SportBusiness;
using Abp.Application.Services;
using Abp.Domain.Repositories;
using SportsPlatform.Model.PermissionManagement;
using MySqlX.XDevAPI.Common;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using SportsPlatform.Query.SportBusiness.Information;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 资讯分类服务
    /// </summary>
    [RemoteService(false)]
    public class CategoryService : SportsPlatformAppServiceBase, ICategoryService
    {

        private readonly IRepository<UserInfo, Guid> _userepository;
        private readonly IRepository<Information, Guid> _newsrepository;
        private readonly IRepository<Category, Guid> _repository;
        private readonly IRepository<CategoryNews, Guid> _categoryNewsRepository;
        private readonly IRepository<CompanyInfo, Guid> _companyRepository;

        public CategoryService(IRepository<Category, Guid> repository, IRepository<UserInfo, Guid> userepository,
            IRepository<Information, Guid> newsrepository, IRepository<CategoryNews, Guid> categoryNewsRepository,
            IRepository<CompanyInfo, Guid> companyRepository, IHttpContextAccessor context) : base(context)
        {
            _userepository = userepository;
            _repository = repository;
            _newsrepository = newsrepository;
            _categoryNewsRepository = categoryNewsRepository;
            _companyRepository = companyRepository;
        }

        /// <summary>
        /// 查询资讯分类分页后的数据
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        public async Task<PagePagingDto<CategoryDto>> GetCategoryDto(GetCategoryQuery query)
        {
            PagePagingDto<CategoryDto> result = new PagePagingDto<CategoryDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var asyncres = await _repository.GetAllListAsync(c => c.IsDeleted == false);
                var res = asyncres.WhereIF(!query.Keywords.IsNullAndEmpty(), c => c.Name.Contains(query.Keywords))
                    .WhereIF(query.CompanyId != null, info => info.CompanyId == query.CompanyId)
                    .WhereIF(query.CompanyId == null && token.CompanyId != null, info => info.CompanyId == token.CompanyId)
                    .WhereIF(query.CompanyId == null && token.CompanyId == null && query.IsPlatform == true, info => info.CompanyId == null || info.CompanyId == Guid.Empty)
                      .OrderByDescending(c => c.CreateTime)
                      .Select(s => new CategoryDto
                      {
                          Id = s.Id,
                          CreateTime = s.CreateTime.ToString("yyyy-MM-dd"),
                          CreateUserId = s.CreateUserId,
                          IsEnable = s.IsEnable,
                          Name = s.Name,
                          ParentId = s.ParentId,
                          CompanyId = s.CompanyId,
                      }).ToList();
                List<CategoryDto> categories = new List<CategoryDto>();
                if (res.Count > 0)
                {
                    var categorylist = await _repository.GetAllListAsync();
                    var userlist = await _userepository.GetAllListAsync();
                    var companylist = await _companyRepository.GetAllListAsync();
                    foreach (var item in res)
                    {
                        if (!item.ParentId.IsNullAndEmpty())
                        {
                            item.ParentName = categorylist.FirstOrDefault(info => info.Id == item.ParentId.Value)?.Name;
                        }
                        else
                        {
                            item.ParentName = "一级分类";
                        }
                        item.CreateUserName = userlist.FirstOrDefault(info => info.Id == item.CreateUserId)?.UserName;
                        item.CompanyName = (item.CompanyId == null || item.CompanyId == Guid.Empty) ? "" : companylist.FirstOrDefault(info => info.Id == item.CompanyId)?.CompanyName;
                        categories.Add(item);
                    }
                    result.TotalCount = categories.Count;
                    var pages = categories.Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize);
                    result.Data = pages;
                    result.IsSuccess = true;
                    result.Code = HttpResultCode.Success;
                    result.Message = "查询成功！";
                    return result;
                }
                else
                {
                    result.Message = "未查询到数据";
                    result.Code = HttpResultCode.NotData;
                }
            }
            catch (Exception e)
            {
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Message = e.Message.ToString();
            }
            return result;
        }

        /// <summary>
        /// 开始添加分类
        /// </summary>
        /// <param name="addCategoryQuery">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddStart(AddCategoryQuery addCategoryQuery)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var res = ObjectMapper.Map<Category>(addCategoryQuery);

                //var user = await _userepository.GetAsync(userid);
                //if (user.IsNullAndEmpty())
                //{
                //    resultDto.Code = HttpResultCode.Success;
                //    resultDto.IsSuccess = true;
                //    resultDto.Message = "当前用户不存在";
                //    return resultDto;
                //}
                res.CreateTime = DateTime.Now;
                res.CreateUserId = token.Id;
                res.CompanyId = token.CompanyId;
                if (!addCategoryQuery.ParentId.IsNullAndEmpty())
                {
                    var Parent = await _repository.GetAsync(addCategoryQuery.ParentId.Value);

                    if (Parent.IsNullAndEmpty())
                    {
                        resultDto.Code = HttpResultCode.Success;
                        resultDto.IsSuccess = true;
                        resultDto.Message = "该分类不存在";
                        return resultDto;
                    }

                    res.ParentId = Parent.Id;
                }

                var category = await _repository.InsertAsync(res);

                resultDto.Code = !category.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !category.IsNullAndEmpty();
                resultDto.Message = !category.IsNullAndEmpty() ? "添加成功" : "添加失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 开始更新资讯分类
        /// </summary>
        /// <param name="updateCategory">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateStart(UpdateCategoryQuery updateCategory)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var res = ObjectMapper.Map<Category>(updateCategory);

                var category = await _repository.GetAsync(updateCategory.Id);

                if (category.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "当前分类不存在";
                    return resultDto;
                }

                var user = await _userepository.GetAsync(token.Id);
                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }

                if (!updateCategory.ParentId.IsNullAndEmpty())
                {
                    var Parent = await _repository.GetAsync(updateCategory.ParentId.Value);

                    if (Parent.IsNullAndEmpty())
                    {
                        resultDto.Code = HttpResultCode.Success;
                        resultDto.IsSuccess = true;
                        resultDto.Message = "该分类不存在";
                        return resultDto;
                    }
                    category.ParentId = Parent.Id;
                }
                else
                {
                    category.ParentId = null;
                }


                var categoryNews = await _categoryNewsRepository.GetAllListAsync(cn => cn.CategoryId == updateCategory.Id && cn.IsDeleted == false);
                if (categoryNews.Count > 0)
                {
                    categoryNews.ForEach(cn =>
                    {
                        var info = _newsrepository.Get(cn.NewsId);
                        info.IsEnable = updateCategory.IsEnable;
                        _newsrepository.Update(info);
                    });
                }


                category.Name = updateCategory.Name;
                category.IsEnable = updateCategory.IsEnable;
                category.UpdateTime = DateTime.Now;
                category.UpdateUserId = user.Id;
                var updatecategory = await _repository.UpdateAsync(category);

                resultDto.Code = !updatecategory.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !updatecategory.IsNullAndEmpty();
                resultDto.Message = !updatecategory.IsNullAndEmpty() ? "更新成功" : "更新失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 开始删除资讯分类
        /// </summary>
        /// <param name="deleteCategoryQuery">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateDeleteCategory(DeleteCategoryQuery deleteCategoryQuery)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var category = await _repository.GetAsync(deleteCategoryQuery.Id);

                if (category.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Error;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "该分类不存在";
                    return resultDto;
                }
                var categoryNews = await _categoryNewsRepository.GetAllListAsync(cn => cn.CategoryId == category.Id && cn.IsDeleted == false);

                if (categoryNews.Count > 0)
                {
                    resultDto.Code = HttpResultCode.Error;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "该分类下存在资讯,不能删除";
                    return resultDto;
                }
                var user = await _userepository.GetAsync(token.Id);
                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }
                category.IsDeleted = true;
                category.DeleteTime = DateTime.Now;
                category.DeleteUserId = user.Id;
                var asyncCategory = await _repository.UpdateAsync(category);

                resultDto.Code = !asyncCategory.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !asyncCategory.IsNullAndEmpty();
                resultDto.Message = !asyncCategory.IsNullAndEmpty() ? "删除成功" : "删除失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message;
                resultDto.IsSuccess = false;
            }
            return resultDto;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="updateSateQuery">传入参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateStateStart(UpdateCategorySateQuery updateSateQuery)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var user = await _userepository.GetAsync(Guid.Parse(AbpSession.UserId.ToString()));
                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }
                var category = await _repository.GetAsync(updateSateQuery.Id);

                if (category.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Error;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "该分类不存在";
                    return resultDto;
                }
                var asyncCategory = await _repository.UpdateAsync(category);
                resultDto.Code = !asyncCategory.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !asyncCategory.IsNullAndEmpty();
                resultDto.Message = !asyncCategory.IsNullAndEmpty() ? "更新状态成功" : "更新状态失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 获取分类列表
        /// </summary>
        /// <returns></returns>
        public async Task<ResultListDto<CategoryDto>> GetAll(Guid? Id, Guid? CompanyId)
        {
            var resultDto = new ResultListDto<CategoryDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                var res = new List<Category>();
                if (Id.IsNullAndEmpty())
                {
                    res = await _repository.GetAllListAsync(c => ((CompanyId != null && CompanyId != Guid.Empty) ? c.CompanyId == CompanyId : c.CompanyId == token.CompanyId) && c.IsDeleted == false && c.IsEnable == true);
                }
                else
                {
                    res = await _repository.GetAllListAsync(c => ((CompanyId != null && CompanyId != Guid.Empty) ? c.CompanyId == CompanyId : c.CompanyId == token.CompanyId) && c.IsDeleted == false && c.IsEnable == true && c.Id != Id);
                }
                resultDto.Count = res.Count;
                resultDto.Code = res.Count > 0 ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = res.Count > 0 ? true : false;
                resultDto.Message = res.Count > 0 ? "查询成功" : "未查询到数据";
                resultDto.Data = res.Count > 0 ? ObjectMapper.Map<List<CategoryDto>>(res) : null;
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 获取该标识下的分类
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetCategoryEditDto>> GetByCategoryId(Guid id)
        {
            var resultDto = new ResultDto<GetCategoryEditDto>();
            try
            {
                var res = await _repository.GetAsync(id);

                if (!res.IsNullAndEmpty())
                {
                    if (!res.ParentId.IsNullAndEmpty())
                    {
                        resultDto.Data = new GetCategoryEditDto
                        {
                            Name = res.Name,
                            ParentId = res.ParentId.Value,
                            IsEnable = res.IsEnable,
                            CompanyId = res.CompanyId,
                        };
                    }
                    else
                    {
                        resultDto.Data = new GetCategoryEditDto
                        {
                            Name = res.Name,
                            ParentId = null,
                            IsEnable = res.IsEnable,
                            CompanyId = res.CompanyId,
                        };
                    }
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "查询成功";

                }
                else
                {
                    resultDto.Code = HttpResultCode.NotData;
                    resultDto.IsSuccess = true;
                    resultDto.Message = "未查询到数据";
                }

            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }
    }
}
